import React, { Component } from 'react';
import { Form, Select, Input, Button, Modal, InputNumber, Upload, Icon, message } from 'antd';
import Tips from '../../Tips/index';
import { connect } from 'react-redux';
import statuscode from '../../statuscode/index';
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;

let uuid = 0;
const Token = localStorage.getItem('token');
class PopForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      installnetwork: '原油链',
      installPath: '',
      installInit: 'init',
      message: '',
      networkdata: [],
      templateId: 0,
      TemplateInit: '',
      args: '',
      inputdata: [],
      selectid: 0,
    };
  }
  tips = (str) => {
    this.setState({
      message: str
    });
    setTimeout(() => {
      this.setState({
        message: ''
      });
    }, 1000);
  }
  template = (ev) => {
    this.setState({
      templateId: ev
    });
  }
  select = (id) => {
    this.setState({
      selectid: id
    });
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        var message = '';
        if (this.state.selectid == 1 && this.props.templatedata.length == 0) {
          message = '暂无模板，无法创建！';
          this.tips(message);
        } else {
          this.props.onCreate(this.state.selectid, values, this.state.templateId, this.state.installPath);
        }
      }
    });
  }
  cancel = () => {
    const onCancel = this.props.onCancel;
    this.setState({ templateId: 0, installPath: '' });
    onCancel();
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.visibleclose) {
      this.cancel();
    }
  }

  render() {
    const { visible } = this.props;
    const { getFieldDecorator } = this.props.form;
    var networkList = '';
    const _this = this;
    const Token = localStorage.getItem('token');
    let templateselect = '';
    const upload = {
      name: 'file',
      showUploadList: false,
      action: '/api/block/chainCode/upload',
      headers: {
        Authorization: Token,
      },
      beforeUpload(file) {
        var fileExt = file.name.substr(file.name.lastIndexOf('.')).toLowerCase();
        if (fileExt != '.go') {
          message.error('文件必须为go文件!');
          return false;
        }
      },
      onChange(response) {
        const responseData = response.file.response;
        console.log(response);
        if (responseData && responseData.code == 200 && response.file.status == 'done') {
          _this.setState({
            installPath: responseData.data,
          });

        } else if (response.file.status == 'error') {
          message.error('上传失败！');
        }
      },
      onRemove(response) {
        _this.setState({
          installPath: ''
        });
      }
    };
    let templatedata = this.props.templatedata;
    if (templatedata) {
      if (templatedata.length == 0) {
        templateselect = (<Option key={0} value={0} disabled >{'暂无模板'}</Option>);
      } else {
        templateselect = templatedata.map((e, i) => {
          return (<Option key={i} value={i} >{e.templateName}</Option>);
        });
      }
    }
    return (
      <div>
        <Modal
          visible={visible}
          title="创建Chaincode"
          onCancel={this.cancel}
          okText="立即提交"
          cancelText="取消"
          closable={false}
          onOk={this.handleSubmit}
          confirmLoading={this.props.timeout}
          className="installModal"
          destroyOnClose={true}
        >
          <div className="selectinstall">
            <div className={this.state.selectid == 0 ? 'select' : ''} onClick={this.select.bind(this, 0)}>上传自建Chaincode</div>
            <div className={this.state.selectid == 1 ? 'select' : ''} onClick={this.select.bind(this, 1)}>安装模板Chaincode</div>
          </div>
          <Form>
            <FormItem
              label="网络"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 16 }}
            >
              <Input value={this.props.changeNetwork} disabled />
            </FormItem>
            <FormItem
              label="Name"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 16 }}
            >
              {getFieldDecorator('ChainCodeName', {
                rules: [{
                  required: true,
                  message: '请输入只包含数字、字母、下划线的ChaincodeName',
                  pattern: /^[0-9a-zA-Z_]{1,}$/
                }],
              })(
                <Input placeholder="请输入ChaincodeName" />
              )}
            </FormItem>
            {this.state.selectid == 1 ? (
              <div>
                <FormItem
                  label="选择模板"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 16 }}
                >
                  <Select onChange={this.template} value={this.state.templateId} >
                    {templateselect}
                  </Select>
                </FormItem>
                {
                  templatedata.length == 0 ? '' : (
                    <FormItem
                      label="模板描述"
                      labelCol={{ span: 6 }}
                      wrapperCol={{ span: 16 }}
                    >
                      <TextArea rows={4} value={templatedata[this.state.templateId].remark} />
                    </FormItem>
                  )
                }
              </div>) :
              (
                <div>
                  <FormItem
                    label="Version"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                  >
                    {
                      getFieldDecorator('Version', {
                        rules: [{
                          required: true,
                          message: '请输入Version'
                        }]
                      })(
                        <Input placeholder="请输入Version" />
                      )}
                  </FormItem>
                  <FormItem
                    label="Path"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                  >
                    {getFieldDecorator('installPath', {
                      rules: [{ required: true, message: '请上传文件' }]
                    })(
                      <div>
                        <Input placeholder="请上传文件" style={{ width: 248 }} value={this.state.installPath} />
                        <Upload {...upload} className="uploadDiv">
                          <Button className="uploadBtn" type="primary">上传文件</Button>
                        </Upload>
                      </div>
                    )}
                  </FormItem>
                </div>
              )}
          </Form>
        </Modal>
        <Tips message={this.state.message} />
      </div>
    );
  }
}
const AddForm = Form.create()(PopForm);
export default connect((state) => {
  return { ...state };
})(AddForm);